/*
  ODARemote.cpp - 
*/

#include "ODARemote.h"
#include "ODPort.h"
#include "WProgram.h"
#include "ODADebug.h"

const uint8_t COMMAND_TIMEOUT = 7; // Timeout del comando in secondi

Remote::Remote() {
  _commandStatus=0;
  _commandCount=0;
  _lastCommand=0;
  return;
}

void Remote::init(uint8_t pinA, uint8_t pinB) {
  _portA.initInput(pinA);
  _portA.setDebounce(100);
  _portB.initInput(pinB);
  _portB.setDebounce(100);
}

void Remote::service() {
  uint8_t statusA = _portA.getStatus();
  
  if (statusA == HIGH) {
    if (_statusA==0) _statusA = 1;
    _commandStatus++;
    _lastCommand = millis();
  } else if (statusA == LOW) {
    _statusA = 0;
  }
  
  if (_commandStatus > 0 && millis() > _lastCommand + (COMMAND_TIMEOUT * 1000)) {
    _commandCount = _commandStatus;
    _commandStatus = 0;
  }

  uint8_t statusB = _portB.getStatus();

  if (statusB == HIGH) {
    if (_statusB==0) _statusB = 1;
    _commandStatus = 0;
    _commandCount = 0;
    _lastCommand = 0;
  } else if (statusB == LOW) {
    _statusB = 0;
  }

}

boolean Remote::getPressA() {
  if (_statusA == 1) {
    _statusA = 2;
    return true;
  } else {
    return false;
  }
}

boolean Remote::getPressB() {
  if (_statusB == 1) {
    _statusB = 2;
    return true;
  } else {
    return false;
  }
}

uint8_t Remote::getCommand() {
  uint8_t ret = _commandCount;
  _commandCount = 0;
  return ret;
}